<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>Spring Boot之基本Web开发 - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-06-26 10:11">
      June 26, 2019 am
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.8k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      28
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-Spring-Boot之基本Web开发"><a href="#学习笔记-Spring-Boot之基本Web开发" class="headerlink" title="学习笔记 : Spring Boot之基本Web开发"></a>学习笔记 : Spring Boot之基本Web开发</h2><h3 id="ServletComponentScan的使用"><a href="#ServletComponentScan的使用" class="headerlink" title="@ServletComponentScan的使用"></a>@ServletComponentScan的使用</h3><p><em>在SpringBootApplication上使用<code>@ServletComponentScan</code>注解后,Servlet、Filter、Listener可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码哟 !</em></p>
<h4 id="开发Servlet"><a href="#开发Servlet" class="headerlink" title="开发Servlet"></a>开发Servlet</h4><ol>
<li><p><em>pom.xml</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
         <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- lookup parent from repository --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">parent</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.1.6.RELEASE<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">relativePath</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">parent</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.yubuntu0109<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>web-servlet<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>web-servlet<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">description</span>&gt;</span>Demo project for Spring Boot<span class="hljs-tag">&lt;/<span class="hljs-name">description</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">java.version</span>&gt;</span>11<span class="hljs-tag">&lt;/<span class="hljs-name">java.version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span></code></pre></div>
</li>
<li><p><em>MyServlet.java : 自定义Servlet</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.web.servlet;

<span class="hljs-keyword">import</span> javax.servlet.annotation.WebServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: web-servlet
 * <span class="hljs-doctag">@description</span>: learn to use the annotation: <span class="hljs-doctag">@ServletComponentScan</span>
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 6/26/2019-9:49 AM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-meta">@WebServlet</span>(name = <span class="hljs-string">"MyServlet"</span>, urlPatterns = <span class="hljs-string">"/helloServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest req, HttpServletResponse resp)</span> </span>&#123;
        System.out.println(<span class="hljs-string">"this's my servlet ~"</span>);
    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>WebServletApplication.java : Spring Boot启动类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.webservlet;

<span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;
<span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;
<span class="hljs-keyword">import</span> org.springframework.boot.web.servlet.ServletComponentScan;

<span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-meta">@ServletComponentScan</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebServletApplication</span> </span>&#123;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        SpringApplication.run(WebServletApplication<span class="hljs-class">.<span class="hljs-keyword">class</span>, <span class="hljs-title">args</span>)</span>;
    &#125;

&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果</em></p>
<div class="hljs"><pre><code class="hljs kotlin"><span class="hljs-keyword">this</span><span class="hljs-string">'s my servlet ~</span></code></pre></div>


</li>
</ol>
<h4 id="开发Filter"><a href="#开发Filter" class="headerlink" title="开发Filter"></a>开发Filter</h4><ol>
<li><p><em>MyFilter.java : 自定义过滤器</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.web.filter;

<span class="hljs-keyword">import</span> javax.servlet.*;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebFilter;
<span class="hljs-keyword">import</span> java.io.IOException;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: web-servlet
 * <span class="hljs-doctag">@description</span>: learn to user annotation: <span class="hljs-doctag">@ServletComponentScan</span>
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 6/26/2019-10:30 AM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>

<span class="hljs-meta">@WebFilter</span>(filterName = <span class="hljs-string">"MyFile"</span>, urlPatterns = <span class="hljs-string">"/helloServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyFilter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Filter</span> </span>&#123;


    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">(FilterConfig filterConfig)</span> </span>&#123;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doFilter</span><span class="hljs-params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="hljs-keyword">throws</span> IOException, ServletException </span>&#123;
        System.out.println(<span class="hljs-string">"this's my filetr !"</span>);
        filterChain.doFilter(servletRequest, servletResponse);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">destroy</span><span class="hljs-params">()</span> </span>&#123;
    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果</em></p>
<div class="hljs"><pre><code class="hljs scala"><span class="hljs-keyword">this</span><span class="hljs-symbol">'s</span> my filetr !
<span class="hljs-keyword">this</span><span class="hljs-symbol">'s</span> my servlet ~</code></pre></div>


</li>
</ol>
<h4 id="开发Listener"><a href="#开发Listener" class="headerlink" title="开发Listener"></a>开发Listener</h4><ol>
<li><p><em>MyListener.java : 自定义监听器</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.web.listener;

<span class="hljs-keyword">import</span> javax.servlet.ServletContextEvent;
<span class="hljs-keyword">import</span> javax.servlet.ServletContextListener;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebListener;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: web-servlet
 * <span class="hljs-doctag">@description</span>: learn to user annotation: <span class="hljs-doctag">@ServletComponentScan</span>
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 6/26/2019-10:54 AM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-meta">@WebListener</span>(value = <span class="hljs-string">"MyListenre"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyListener</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ServletContextListener</span> </span>&#123;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">contextInitialized</span><span class="hljs-params">(ServletContextEvent sce)</span> </span>&#123;
        System.out.println(<span class="hljs-string">"this's contextInitialized ~"</span>);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">contextDestroyed</span><span class="hljs-params">(ServletContextEvent sce)</span> </span>&#123;
        System.out.println(<span class="hljs-string">"this's contextDestroyed ~"</span>);
    &#125;

&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果</em></p>
<div class="hljs"><pre><code class="hljs scala"><span class="hljs-keyword">this</span><span class="hljs-symbol">'s</span> requestInitialized ~
<span class="hljs-keyword">this</span><span class="hljs-symbol">'s</span> my filetr !
<span class="hljs-keyword">this</span><span class="hljs-symbol">'s</span> my servlet ~
<span class="hljs-keyword">this</span><span class="hljs-symbol">'s</span> requestDestroyed ~</code></pre></div>



</li>
</ol>
<h3 id="使用Bean注解注册Servlet等组件"><a href="#使用Bean注解注册Servlet等组件" class="headerlink" title="使用Bean注解注册Servlet等组件"></a>使用Bean注解注册Servlet等组件</h3><p><em>WebServletApplication.java : Spring Boot启动类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.web;

<span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;
<span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;
<span class="hljs-keyword">import</span> org.springframework.boot.web.servlet.FilterRegistrationBean;
<span class="hljs-keyword">import</span> org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
<span class="hljs-keyword">import</span> org.springframework.boot.web.servlet.ServletRegistrationBean;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;
<span class="hljs-keyword">import</span> pers.huangyuhui.web.filter.MyFilter;
<span class="hljs-keyword">import</span> pers.huangyuhui.web.listener.MyListener;
<span class="hljs-keyword">import</span> pers.huangyuhui.web.servlet.MyServlet;

<span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebServletApplication</span> </span>&#123;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;

        SpringApplication.run(WebServletApplication<span class="hljs-class">.<span class="hljs-keyword">class</span>, <span class="hljs-title">args</span>)</span>;
    &#125;

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-comment">//使用@Bean注解注册Servlet</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> ServletRegistrationBean <span class="hljs-title">getServletRegistration</span><span class="hljs-params">()</span> </span>&#123;
        ServletRegistrationBean servletRegistrationBean = <span class="hljs-keyword">new</span> ServletRegistrationBean(<span class="hljs-keyword">new</span> MyServlet());
        servletRegistrationBean.addUrlMappings(<span class="hljs-string">"/Bean-helloServlet"</span>);
        <span class="hljs-keyword">return</span> servletRegistrationBean;
    &#125;
    <span class="hljs-comment">/*the result:
        this's my servlet ~
     */</span>

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-comment">//使用@Bean注解注册Filter</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> FilterRegistrationBean <span class="hljs-title">getFilterRegistrationBean</span><span class="hljs-params">()</span> </span>&#123;
        FilterRegistrationBean filterRegistrationBean = <span class="hljs-keyword">new</span> FilterRegistrationBean(<span class="hljs-keyword">new</span> MyFilter());
        filterRegistrationBean.addUrlPatterns(<span class="hljs-string">"/Bean-helloServlet"</span>);
        <span class="hljs-keyword">return</span> filterRegistrationBean;
    &#125;
    <span class="hljs-comment">/*the result:
        this's my filetr !
        this's my servlet ~
     */</span>

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-comment">//使用@Bean注解注册Listener</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> ServletListenerRegistrationBean <span class="hljs-title">getServletListenerRegistrationBean</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ServletListenerRegistrationBean(<span class="hljs-keyword">new</span> MyListener());
    &#125;
     <span class="hljs-comment">/*the result:
        this's contextInitialized ~
     */</span>

&#125;</code></pre></div>



<h3 id="静态资源访问"><a href="#静态资源访问" class="headerlink" title="静态资源访问"></a>静态资源访问</h3><h4 id="默认策略"><a href="#默认策略" class="headerlink" title="默认策略"></a>默认策略</h4><p><em>简介 : Spring Boot默认会过滤所有的静态资源,而静态资源的位置一共有5个,如下所示. 注意: 按照定义的顺序,5个静态资源位置的优先级依次降低! 但是一般情况下,Spring Boot项目不需要<code>webapp</code>目录,所以在第5个”<code>/</code>“可以暂时不考虑哟 ~</em></p>
<ol>
<li><em>classpath:/META-INF/resources/</em></li>
<li><em>classpath:/resources/</em></li>
<li><em>classpath:/static/</em></li>
<li><em>classpath:/pulic/</em></li>
<li><em>/</em></li>
</ol>
<ul>
<li><em>扩 : 如果你使用的是Intellij IDEA开发工具,记得设置<code>目录类型</code>哟 !</em></li>
</ul>
<h4 id="自定义策略"><a href="#自定义策略" class="headerlink" title="自定义策略"></a>自定义策略</h4><p><em>如果默认的静态资源过滤策略不能满足开发需求,也可以自定义资源过滤策略,自定义静态资源过滤策略有如下两种方式 :</em></p>
<ol>
<li><em>在配置文件中定义</em></li>
<li><em>Java编码定义</em></li>
</ol>
<p><em>第一种方式示例 : 可以在<code>application.properties</code>中直接定义过滤规则(第一行)和静态资源位置(第二行),示例代码如下 :</em></p>
<div class="hljs"><pre><code class="hljs gradle">spring.mvc.<span class="hljs-keyword">static</span>-path-pattern=<span class="hljs-regexp">/static/</span>**
spring.resources.<span class="hljs-keyword">static</span>-locations=<span class="hljs-keyword">classpath</span>:<span class="hljs-regexp">/static/</span></code></pre></div>



<h3 id="文件的上传"><a href="#文件的上传" class="headerlink" title="文件的上传"></a>文件的上传</h3><p><em>简介 : 多数文件上传都是通过表单形式提交给服务器的,因此,要实现文件上传功能就需要提供一个上传文件的表单,而此表单必须满足以下三个条件.</em></p>
<ol>
<li><em>form表单的method的属性设置为post</em></li>
<li><em>form表单的enctype属性设置为multipart/form-data</em></li>
<li><em>提供<code>&lt;input type=&quot;file&quot; name=&quot;filename&quot;/&gt;</code>的文件上传输入框</em></li>
</ol>
<p><em>在Spring Boot中可以根据需要在<code>application.properties</code>中对上传的文件进行详细的配置,示例代码如下 :</em></p>
<div class="hljs"><pre><code class="hljs ini"><span class="hljs-attr">spring.servlet.multipart.enabled</span>=<span class="hljs-literal">true</span>
<span class="hljs-attr">spring.servlet.multipart.file-size-threshold</span>=<span class="hljs-number">0</span>
<span class="hljs-attr">spring.servlet.multipart.location</span>=D://upload//photo
<span class="hljs-attr">spring.servlet.multipart.max-file-size</span>=<span class="hljs-number">5</span>MB
<span class="hljs-attr">spring.servlet.multipart.max-request-size</span>=<span class="hljs-number">10</span>MB
<span class="hljs-attr">spring.servlet.multipart.resolve-lazily</span>=<span class="hljs-literal">false</span></code></pre></div>
<ol>
<li><em>第一行: 设置是否开启文件上传支持,默认为true</em></li>
<li><em>第二行: 设置文件写入磁盘的阈值,默认为0</em></li>
<li><em>第三行: 指定上传文件的临时保存位置</em></li>
<li><em>第四行: 设置上传的单个文件的最大大小,默认为1MB</em></li>
<li><em>第五行: 设置多文件上传时文件的总大小,默认为10MB</em></li>
<li><em>第六行: 设置文件是否延迟解析,默认为false</em></li>
</ol>
<h4 id="示例程序"><a href="#示例程序" class="headerlink" title="示例程序"></a>示例程序</h4><p><em>upload.html : 上传文件页面</em></p>
<div class="hljs"><pre><code class="hljs html"><span class="hljs-meta">&lt;!DOCTYPE html&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Title<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- 验证表单信息 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="javascript">
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">check</span>(<span class="hljs-params"></span>) </span>&#123;
            <span class="hljs-keyword">var</span> file = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"file"</span>).value;
            <span class="hljs-keyword">if</span> (file.length === <span class="hljs-number">0</span> || file === <span class="hljs-string">""</span>) &#123;
                alert(<span class="hljs-string">"请选择需要上传的文件 !"</span>);
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
            &#125;
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        &#125;
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"../fileUpload"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span> <span class="hljs-attr">enctype</span>=<span class="hljs-string">"multipart/form-data"</span> <span class="hljs-attr">onsubmit</span>=<span class="hljs-string">"return check()"</span>&gt;</span>
    请选择文件 <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"uploadfile"</span>/&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"上传"</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre></div>

<p><em>FileController.java : 操控文件的控制器</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.web.controller;

<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RestController;
<span class="hljs-keyword">import</span> org.springframework.web.multipart.MultipartFile;

<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> java.io.File;
<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.util.UUID;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: web-servlet
 * <span class="hljs-doctag">@description</span>: 操控文件的控制器
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 6/26/2019-4:34 PM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FileController</span> </span>&#123;

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@description</span>: 上传文件
     * <span class="hljs-doctag">@param</span>: uploadfile
     * <span class="hljs-doctag">@param</span>: request
     * <span class="hljs-doctag">@date</span>: 2019-06-26 5:00 PM
     * <span class="hljs-doctag">@return</span>: java.lang.String
     */</span>
    <span class="hljs-meta">@RequestMapping</span>(<span class="hljs-string">"/fileUpload"</span>)
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">handleFormUpload</span><span class="hljs-params">(MultipartFile uploadfile, HttpServletRequest request)</span> </span>&#123;
        <span class="hljs-keyword">if</span> (!uploadfile.isEmpty() &amp;&amp; uploadfile.getSize() &gt; <span class="hljs-number">0</span>) &#123;
            <span class="hljs-comment">//获取上传文件的原始名称</span>
            <span class="hljs-keyword">final</span> String originFileName = uploadfile.getOriginalFilename();
            <span class="hljs-comment">//指定上传文件的保存目录</span>
            <span class="hljs-keyword">final</span> String dirPath = request.getServletContext().getRealPath(<span class="hljs-string">"/upload/photo/"</span>);
            <span class="hljs-comment">//若保存文件的目录不存在,则创建该目录</span>
            File file = <span class="hljs-keyword">new</span> File(dirPath);
            <span class="hljs-keyword">if</span> (!file.exists()) &#123;
                file.mkdirs();
            &#125;
            <span class="hljs-comment">//使用UUID重命名文件名称(uuid__原始文件名称)</span>
            <span class="hljs-keyword">final</span> String newFileName = UUID.randomUUID() + <span class="hljs-string">"__"</span> + originFileName;
            <span class="hljs-keyword">try</span> &#123;
                <span class="hljs-comment">//将上传的文件保存到目标目录下</span>
                uploadfile.transferTo(<span class="hljs-keyword">new</span> File(dirPath + newFileName));
            &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;
                e.printStackTrace();
            &#125;
            <span class="hljs-keyword">return</span> <span class="hljs-string">"success to upload the file !"</span>;
        &#125;
        <span class="hljs-keyword">return</span> <span class="hljs-string">"fail to upload the file !"</span>;
    &#125;

&#125;</code></pre></div>
            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Spring-Boot/">Spring Boot</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/06/26/Spring-Boot%E4%B9%8B%E6%95%B4%E5%90%88%E8%A7%86%E5%9B%BE%E5%B1%82%E6%8A%80%E6%9C%AF/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Spring Boot之整合视图层技术</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/06/25/Hi-Redis/">
                        <span class="hidden-mobile">Hi Redis ~</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Spring Boot之基本Web开发&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
